package cn.com.chengq.oa;

import java.io.*;
import java.security.SecureClassLoader;

/**
 * 从后缀名称是*.myclass文件中加载类
 */
public class SalaryClassLoader extends SecureClassLoader {
    // 自定义的类加载路径
    private String classPath;

    public SalaryClassLoader(String classPath) {
        this.classPath = classPath;
    }

    /**
     * 需要实现从*.myclass文件中加载类
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        if (b == null || b.length == 0) {
            throw new ClassNotFoundException(name);
        }
        return defineClass(name, b, 0 , b.length);
    }

    private byte[] loadClassData(String name) {
        String filePath = this.classPath + name.replace(".", "\\").concat(".myclass");
        System.out.println(filePath);

        File file = new File(filePath);
        byte[] buffer = new byte[1024];

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            new ClassNotFoundException(name, e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != baos) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return baos.toByteArray();
    }
}
